package com.example.listener;

import com.example.po.SysServer;
import com.example.service.SysServerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @className: SysServerListener
 * @author: chentao
 * @date: 2025/8/29 9:00
 * @Version: 1.0
 * @description:
 */
@Service
public class SysServerListener implements InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${sys.server.heartbeat.period}")
    private int period;

    @Resource
    private SysServerService sysServerService;

    private ScheduledExecutorService scheduledExecutorService;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.scheduledExecutorService = Executors.newScheduledThreadPool(10);
        this.scheduledExecutorService.scheduleAtFixedRate(new SysServerHearbeat(), 0, period, TimeUnit.SECONDS);
        logger.warn("serverKey {} started ..", sysServerService.getServerKey());
    }

    @Override
    public void destroy() throws Exception {
        if (this.scheduledExecutorService != null) {
            this.scheduledExecutorService.shutdownNow();
        }
    }

    class SysServerHearbeat implements Runnable {

        @Override
        public void run() {
            SysServer sysServer = new SysServer();
            sysServer.setId(sysServerService.getServerKey());
            sysServer.setRefreshTime(new Date());
            sysServer.setServerKey(sysServerService.getServerKey());
            sysServer.setDownTime(null);
            sysServer.setActive(true);
            sysServer.setIp(sysServerService.getIp());
            sysServer.setPort(sysServerService.getPort());
            sysServer.recalculateFields();
            sysServerService.saveOrUpdate(sysServer);
        }
    }
}
